# -*- encoding: utf-8 -*-
import flask
from flask import request
import json
import requests
import hmac
import base64
import hashlib

server = flask.Flask(__name__)

# 消息数字签名计算核对
def check_sign(timestamp):
    app_secret = 'PSCUfpo86sV5wW1RexKIGlyoQ_ngpYdnNyT799pda41DKtC2l9GqsHAiDSZFw_j4'
    app_secret_enc = app_secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, app_secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(app_secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = base64.b64encode(hmac_code).decode('utf-8')
    return sign


# 发送text消息
def send_text_msg(userid, message, webhook_url):
    message_json = {
        "msgtype": "text",
        "text": {
            "content": message
        },
        "at": {
            "atDingtalkIds": [userid],
            "isAtAll": False
        }
    }
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    # 返回发送状态
    info = requests.post(url=webhook_url, json=message_json, headers=header)


# 处理自动回复消息
def handle_info(req_data):
    # 解析用户发送消息 通讯webhook_url
    text_info = req_data['text']['content'].strip()
    webhook_url = req_data['sessionWebhook']
    senderid = req_data['senderId']
    # print('***************text_info：', text_info)
    # if判断用户消息触发的关键词，然后返回对应内容
    # python3.10 以上还可以用 switch case...
    # 调用函数，发送markdown消息
    text = '这是响应内容,你的请求内容是：%s' % (text_info)
    send_text_msg(senderid, text, webhook_url)


@server.route("/", methods=['post'])
def get_data():
    # 第一步验证：是否是post请求
    if request.method == "POST":
        # print(request.headers)
        # 签名验证 获取headers中的Timestamp和Sign
        timestamp = request.headers.get('Timestamp')
        sign = request.headers.get('Sign')
        # 第二步验证：签名是否有效
        if check_sign(timestamp) == sign:
            # 获取、处理数据
            req_data = json.loads(str(request.data, 'utf-8'))
            # print(req_data)
            # 调用数据处理函数
            handle_info(req_data)
            print('验证通过')
            return 'p_pass'

        print('验证不通过')
        return 'p_no_pass'

    print('有get请求')
    return 'p_get'

if __name__ == '__main__':
    server.run(host="0.0.0.0", port=8083)
